<template>
<view >
  <!--  -->
   <view  v-if="phoneInfoVisible">
      <view class="flex-column-center container">
        <image class="logo" src="./../../static/logo.png" alt="">
         <text class="ft44 mgb20">智城云充</text>
      </view>
     <button
      open-type="getPhoneNumber"
      @getphonenumber="getPhoneNumber"
      lang="zh_CN"
      type="primary"
      class="authBtn mg50-y"
    >手机号快捷登录</button>
   </view>

   <view   v-if="!phoneInfoVisible" >
 <view class="radius-16 bgw flex mg20-y mgt200 ft32 ftr "
 >
 
   <view class="ta wNote pd50-x" >    
     <h3 style="font-weight:700">注意事项:</h3> 
      <view>①:使用范围为选定地区 <span style="font-weight:700">(省份)</span>;</view>
      <!-- <view>①:选择充电桩使用的地区(省份)，选定后只能使用该省充电桩;</view> -->
      <!-- 使用范围为选定地区(省份) -->
      <view>②:选定地区后无法修改</view>
   </view>
 </view>
 <view class="radius-16 bgw flex mg20-y mgt20 ft30" 
     style="width=720rpx"
     @tap="showAddress">
       <!-- <view class=" mgl30">
          <text class="ftr ft28">(必选)</text>
          <text>使用地区:</text>
       </view> -->
        <view class="flex1">
          <input class="txt inpBot radius-16" 
          style="text-align:center"
          v-model="pca" disabled type="text" placeholder="点击选择地区">
        </view>
      </view>
  <!-- <i-panel title="选择使用的地区">
      <i-input v-model="pca"  title="选择使用的地区"  autofocus  placeholder="请选择所在地区,一旦确认后不可更改"  mode="wrapped" />    
      </i-panel>  -->

 <view class="flex-column-center container">

    <!--
    <image class="logo" :src='logo'></image>
    <text class="ft44 mgb20">{{appName}}</text>
    -->
    
    <text class="ft24 dlc-gray mg10-y">申请获取你的公开信息（昵称、头像等）</text>
     <view class="flex flex-wrap authDes"> 
      <!-- <label class="checkbox"> -->
    <checkbox  :checked="isChecked" @click="changeisChecked"  class="authSel"/>
     <!-- </label> -->
      <view  @click="changeUrl" class="readInfo">我已详细阅读并同意该服务协议</view>
       </view>

    <button
      @click="getUserInfoEvent"
      lang="zh_CN"
      type="primary"
      class="authBtn mg50-y"
    >确认信息</button>

    </view>
     <!-- 省市区弹窗 -->
    <van-popup :show="areaShow" position="bottom" :overlay="true">
        <van-area title="选择地区"  
        :columns-placeholder="['请选择', '请选择', '请选择']"
        :area-list="areaList" 
        @confirm="onSelect"
        @cancel="areaShow = false" 
        />
    </van-popup>
  </view>
   <i-message id="message" />
    <i-toast id="toast" />
</view>
</template>
<script>
import store from "@/store";
import { authorization, register,getPhone } from "@/api";
import areaList from '@/utils/area';
import { REQUEST_BASE_URL } from "@/config";
const { $Toast } = require("@/wxcomponents/iview/base/index");
const { $Message } = require("@/wxcomponents/iview/base/index");
export default {
  data() {
    return {
      areaShow:false,
      pca:"",
      areaList:areaList,
      province:"",
      city:"",
      area:"",
      authVisi: false,
      actions: [
        {
          name: "去绑定",
          color: "#2d8cf0"
        }
      ],
      userInfo: {},
      logo: null,
      appName: "",
      isChecked:false,
      query:{openId:"",
      },
      phoneInfo:{
        encryptedData:"",
        iv:"",
        sessionKey:""
      },
      phoneInfoVisible:true,
      userPhone:null,
    };
  },
  methods: {
   showAddress(){
     this.areaShow=true
   },
   onSelect(e){
    this.pca= e.detail.values[0].name+"-"+
    e.detail.values[1].name+"-"+e.detail.values[2].name
    this.province=e.detail.values[0].name
    this.city=e.detail.values[1].name
    this.area=e.detail.values[2].name
    this.areaShow=false
   },
   async getUserInfoEvent() {
        if(this.pca){
          if(this.isChecked){
            console.log(this.isChecked) 
          // if (e.mp.detail.errMsg === "getUserInfo:ok"){
            //调用服务器接口
			wx.getUserProfile({
				desc: "获取你的昵称、头像、地区及性别",
				success: res => {
					console.log(res,'res222')
					this.userInfo = res.userInfo
					this.register();
				},
				fail: err => {
					  $Toast({
					    content: "您拒绝了授权",
					    type: "warning",
					    duration: 3000
					  });
					},
				})
			}
          // this.userInfo = await e.mp.detail.userInfo;
          // console.log(e.mp.detail.userInfo)
          // this.register();
        // }
        // else {
        //   $Toast({
        //     content: "您拒绝了授权",
        //     type: "warning",
        //     duration: 3000
        //   });
        // }

       else{
          $Toast({
            content: '请阅读服务协议并勾选',
            type: 'warning',
            duration:3000
          }); 
         }
        }
        else{
          $Toast({
            content: '请选择使用的省',
            type: 'warning',
            duration:3000
          }); 
        }
    },
    async getPhoneNumber(e){
       this.phoneInfo.encryptedData =e.target.encryptedData
       this.phoneInfo.iv =e.target.iv
       const {data} = await getPhone({
       ...this.phoneInfo
      })
      if(data.code==1){
        let phoneNum=JSON.parse(data.data)
        this.phoneNum=phoneNum.phoneNumber
        console.log(this.phoneNum)
        $Message({
            content:"登录成功，请按照提示选取地区",
            type: "success",
            duration:2
          })
        
        this.phoneInfoVisible=false       
      }else{
          $Message({
            content:"登录失败",
            type: "error",
            duration:2
          })
      }
      console.log(data,'data')
    },
    changeisChecked(){
         this.isChecked = ! this.isChecked 
       },

    changeUrl(){
         uni.navigateTo({
           url:"agreement"
         })
       },
     async auth(option) {
      let [a, { code, errMsg }] = await uni.login();

      if (errMsg === "login:ok") {
        //调用服务器接口
        const { data } = await authorization({ code });
        if (data.code === 1) {
          const { Authorization, openId,sessionKey } = data.data;
          if (Authorization) {
            //刷新token,和第一次进来getUserInfo
            store.commit("set_token", Authorization);
            await store.dispatch("getUserInfo");
          } 
          this.query.openId=openId
          this.phoneInfo.sessionKey=sessionKey
          console.log(this.query)
          // else {
          //   uni.redirectTo({
          //     url: `/pagesA/auth/index?openId=${openId}`,
          //   });
          // }
        } else {
          return Promise.reject();
        }
      }
    },   
    async register(e){
     if(this.province&&this.city&&this.area){
       let params = {
        nickName: this.userInfo.nickName,
        avatarUrl: this.userInfo.avatarUrl,
        openId: this.query.openId,
        city:this.city,
        province:this.province,
        area:this.area,
        userPhone:this.phoneNum
      };
      //调用服务器接口
      const { data } = await register(params);
      if (data.code === 1) {
        console.log(data.data)
        store.commit("set_token",data.data);
        $Toast({
          content: "授权成功",
          duration: 1000
        });
        setTimeout(() => {
          uni.switchTab({
           url: '/pages/order/inputCode'
          });
        }, 500);
       
      }
     }else{
        $Toast({
          content: "请选择你所在的地区",
          type:"warning",
          duration: 2000
        });
     }
    }
   },
  onReady(){
    
  //  store.dispatch('getSystemParam',1).then(res =>{
  //       if (res.code === 1) {
  //         this.logo = REQUEST_BASE_URL + res.data.parameter
  //         this.$forceUpdate()
  //       }
  //     })
  //  store.dispatch('getSystemParam',2).then(res =>{
  //       if (res.code === 1) {
  //         this.appName = res.data.parameter
  //       }
  //     })
  },
  onLoad(query) {
	  if(!query.openId){
		  $Toast({
		    content: "请先登录",
		    type:"none",
		    duration: 2000
		  });
	  }
   this.auth()
    // this.query = { ...query };
  },
  onUnload(){
 
  }
};
</script>

<style lang="stylus" scoped>
.logo {
  margin: 100rpx 0 50rpx 0;
  width: 240rpx;
  height: 240rpx;
  border-radius: 50%;
}
.authBtn {
  width: 90%;
}
.inpBot{
  height 60rpx
  width 500rpx
  margin 10rpx auto
  border:1rpx solid #ccc
  text-align left 
  text-indent 10rpx

  }
.wNote
  width 750rpx
.readInfo
  color #2278bf; 
.authDes
  height 80rpx;
.authSel
   vertical-align middle;
   margin-top -2rpx;
   margin-bottom 1rpx;
</style>
